package com.bignerdranch.android.ecar.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;

import com.android.volley.Response;
import com.bignerdranch.android.ecar.Activity.BaseActivity;
import com.bignerdranch.android.ecar.Adapter.NewsAdapter;
import com.bignerdranch.android.ecar.R;
import com.bignerdranch.android.ecar.Utils.RequestUtil;
import com.bignerdranch.android.ecar.Utils.URLBank;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class NewsListActivity extends BaseActivity implements View.OnClickListener {

    private ImageButton news_list_back;
    private JSONArray mData;
    private ListView mListView;
    private NewsAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_list);
        initView();
        initData();
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(NewsListActivity.this,NewsDetailActivity.class);
                intent.putExtra("position",position);
                startActivity(intent);
//                Log.e("=mListView=====",position+"");

            }
        });

    }

    private void initView() {
        news_list_back = (ImageButton) findViewById(R.id.news_list_back);

        mListView = (ListView) findViewById(R.id.news_list);
        news_list_back.setOnClickListener(this);
    }
    private void initData(){
        RequestUtil.executeJSONObject(this, URLBank.news_url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject o) {
                try {
                    JSONArray array = o.getJSONArray("data");
                    mAdapter = new NewsAdapter(getApplicationContext(),array);
                    mListView.setAdapter(mAdapter);
                    mAdapter.notifyDataSetChanged();
//                    Log.e("====url==",URLBank.news_url);
//                    Log.e("====array==",array.length()+"");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.news_list_back:

                finish();
                break;
        }
    }
}
